package com.cykj.page05;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page05
 * @Author: 阿隆
 * @CreateTime: 2025-10-18 16:19
 * @Description: TODO
 * @Version: 1.0
 */
public class ThreeServe {
    public static void main(String[] args) {
        try {
            //创建ServerSocket => 服务器
            ServerSocket serverSocket = new ServerSocket(9090);

            System.out.println("服务端启动端口号为: 9090");

            //等待客户端连接  阻塞
            Socket socket = serverSocket.accept();

            //读取客户端发送的消息
            InputStream is = socket.getInputStream();

            byte[] bytes = new byte[1024];

            //读取
            int len = is.read(bytes);

            //请求消息
            String request = new String(bytes, 0, len);
            //按照回车换行切割
            String[] requestMsgArray = request.split("\r\n");

            //获取请求行
            String requestLine = requestMsgArray[0];

            //按照空格切割请求行
            String[] requestLineArray = requestLine.split(" ");

            //获取请求URL
            String requestURL = requestLineArray[1];

            System.out.println("requestURL = " + requestURL);

//            System.out.println(Arrays.toString(requestLineArray));


            /*
             * http://127.0.0.1:9090/pages/index.html
             * http://127.0.0.1:9090/images/123.png
             * */
            FileInputStream fis = new FileInputStream("webapps" + requestURL);
            byte[] bytesImg = new byte[fis.available()];

            fis.read(bytesImg);

            //给浏览器响应消息
            OutputStream os = socket.getOutputStream();
            os.write("HTTP/1.1 200 OK".getBytes());
            os.write("\r\n".getBytes());  //回车换行
            os.write("Content-Type: text/html; charset=utf-8".getBytes());   //动态获取媒体类型如何解决?
            os.write("\r\n".getBytes());  //回车换行
            os.write(("Content-Length: " + bytesImg.length).getBytes()); //大小 字节大小
            os.write("\r\n".getBytes());  //回车换行
            os.write("\r\n".getBytes());  //回车换行
            os.write(bytesImg);


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
